package com.xhl.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.xhl.gateway.config.WhiteListConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Author xhl
 * @Date 2022/12/26 13:56
 **/
@Component
@Slf4j
public class TokenCheckFilter implements GlobalFilter, Ordered {

    // UserTokenRepository 负责用户 token 的存储和校验，读者可以根据项目实际情况进行实现
//    @Autowired
//    private UserTokenRepository userTokenRepository;

    @Autowired
    private WhiteListConfig whiteListConfig;

    private static final PathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR 由 RouteToRequestUrlFilter 放入
        URI url = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);

        if (url == null){
            return chain.filter(exchange);
        }

        // 请求的服务名，也就是
        String host = url.getHost();
        // 获取白名单列表
        Map<String, List<String>> whiteListMap = whiteListConfig.getWhiteListMap();
        // 请求的路径
        String path = url.getPath();

        if (whiteListMap != null){

            List<String> whiteList = whiteListMap.get(host);

            if (!CollUtil.isEmpty(whiteList)){
                for (String white : whiteList) {
                    // 如果下面的 if 为 true，说明请求的是白名单中的接口，直接放行即可
                    if (StrUtil.isNotEmpty(white) && PATH_MATCHER.match(white,path)){
                        return chain.filter(exchange);
                    }else {
                        log.info("请求不在白名单内，请求被拦截~");
                    }
                }
            }

        }

        // 后面的逻辑就是校验用户 token 是否有效，根据项目情况实现即可
        return null;
    }

    // 定义该 filter 的执行顺序，该 filter 需要排在 RouteToRequestUrlFilter 的后面
    @Override
    public int getOrder() {
        return 10050;
    }
}
